package top.gbiot.scan.service;

import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

@Service
public class IoApiService  {
    public String api="/api/system/get/netInfo";

    String ip="192.168.1.1"  ;

    public String api( String apiPath,String httpMethod ) throws IOException {
        String body="";
        URL url = new URL(apiPath);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setConnectTimeout(3000); //3秒超时
        String input = "{\"username\":\"hxgk\", \"password\":\"hxgk1234\"}";
        int status=-1;
        String message="";
        try {
            String m = httpMethod;
            conn.setRequestMethod(m);
            conn.setRequestProperty("Content-Type", "application/json; utf-8");
            conn.setRequestProperty("Accept", "application/json");
            conn.setDoOutput(true);
            int resCode = conn.getResponseCode();
            System.out.println(apiPath+" 当前连接状态："+ resCode);
            // "post","put"请求
            if ( httpMethod.equalsIgnoreCase("post")|| httpMethod.equalsIgnoreCase("put") ) {
                OutputStream os = conn.getOutputStream();
                byte[] inputBytes = input.getBytes(StandardCharsets.UTF_8);
                os.write(inputBytes);
                os.flush();
            }

            //获取http响应结果
            status = conn.getResponseCode();
            message =  conn.getResponseMessage();

            //读取设备返回信息
            String texts;
            BufferedReader ins = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            StringBuilder content = new StringBuilder();
            while( (texts = ins.readLine()) != null) {
                content.append(texts);
            }
            ins.close();
            body = content.toString();

        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if ( null != conn) {
                conn.disconnect();;
            }
        }

        //System.out.println("Status code: " + status);
        //System.out.println("Return massage: " + message);

        //http请求扫描设备成功
        if (200==status || message.equalsIgnoreCase("ok")) {
            System.out.println( "OK api interface: "+apiPath+" ， body content: " + body);
        } else {
            System.out.println( "Not api interface: "+apiPath+" ， body content: " + body);
        }
        return body;
    }
}
